package com.krui.iwebo.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 数据库封装类
 * @author krui
 *
 */
public final class DataBaseHelper {
	
	/** TAG*/
	private static final String TAG = "DataBaseManager";
	
	/** database version*/
	private static final int DB_VERSION = 1;
	
	/** context for Android app*/
	private Context mContext;
	
	/** database name*/
	private String  dataBaseName;
	
	/** database*/
	private DatabaseHelper mSQLiteDataBaseHelper;
	
	/** read database */
	private SQLiteDatabase mSQLiteDatabaseRead;
	
	/** write database */
	private SQLiteDatabase mSQLiteDatabaseWrite;
	
	/** database instance*/
	private static DataBaseHelper _instance;
	
	/** Inner class. databaseHelper*/
	
	private class DatabaseHelper extends SQLiteOpenHelper{
		

		public DatabaseHelper() {
			super(mContext, dataBaseName, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS notes");
			onCreate(db);
		}
		
	}
	
	/**
	 * private constructor
	 * @param mContext
	 * @param dbName
	 */
	private DataBaseHelper(Context mContext,String dbName){
		this.mContext = mContext;
		dataBaseName = dbName;
		mSQLiteDataBaseHelper = new DatabaseHelper();
		mSQLiteDatabaseRead = mSQLiteDataBaseHelper.getReadableDatabase();
		mSQLiteDatabaseWrite = mSQLiteDataBaseHelper.getWritableDatabase();
		Log.d(TAG, "load database...");
		
	}
	
	
	/**
	 * get instance from database manager
	 * @param context
	 * @param dbName
	 * @return
	 */
	public static final DataBaseHelper getInstance(Context context,String dbName){
		if (_instance == null && context != null) {
			_instance = new DataBaseHelper(context, dbName);
		}
		return _instance;
	}
	
	
	 /**
     * get read database
     * @return
     */
    public final SQLiteDatabase getReadDatabase() {
        return mSQLiteDatabaseRead;
    }

    /**
     * get write database
     * @return
     */
    public final SQLiteDatabase getWriteDatabase() {
        return mSQLiteDatabaseWrite;
    }

    /**
     * execute sql
     * @param sql
     */
    public final void execSQL(String sql) throws Exception {
        mSQLiteDatabaseWrite.execSQL(sql);
    }
    
    /**
     * excute query sql
     * @param sql
     * @param selectionArgs
     * @throws Exception
     */
    public final void execRawQuery(String sql,String[] selectionArgs) throws Exception{
    	mSQLiteDatabaseRead.rawQuery(sql, selectionArgs);
    }

    /**
     * delete database from application private area
     */
    public final void deleteDatabse() {
        mContext.deleteDatabase(dataBaseName);
    }
}
